package org.bite;

import java.sql.*;
import java.text.MessageFormat;

public class Demo01_DriverManager {

    public static void main(String[] args) {

        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;

        try {
            //1.加载数据库厂商的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2.获取数据库的连接
              connection= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false",
                    "root",
                    "123456"
                    );

           //3.创建Statement对象(用于执行静态的SQL语句并返回执行结果)
              statement= connection.createStatement();

           //4.定义SQL语句
            String sql="select * from student";

           //5.执行SQL语句
              resultSet = statement.executeQuery(sql);/* 查询,会返回结果集对象 用ResultSet接收 */
            //statement.executeUpdate(sql);/* 增删改(更新) */

           //6.遍历结果集
            while(resultSet.next()){//初始游标为第一行前,next()到下一行
                //获取具体列的值 用相应的数据类型接收(或者创建对象接收)
                //resultSet.getLong(1); 通过列名或者顺序获取
                long id=resultSet.getLong("id");
                String name=resultSet.getString("name");
                String sno=resultSet.getString("sno");
                int age=resultSet.getInt("age");
                System.out.println(MessageFormat.format("学生编号={0},学号={1},姓名={2},年龄={3}",id,sno,name,age));
                //格式化输出字符串 数字为占位符
            }

            //7.断开数据库连接 (释放相应的类,在finally中释放,后创建的先释放)

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
           //释放结果集对象
            if (resultSet == null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            //释放Statement
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            //关闭数据库连接
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
